var _ajax = $.ajax;
$.ajax = function(opt){
    //签名
    var sign = '3L7bfO3OBjucxpuVK+gO0g=='
  

    if(opt.headers){
        opt.headers.sign = sign
        opt['X-Requested-With'] = 'XMLHttpRequest'
       
    }else{
        opt.headers = {
            sign:sign,
            'X-Requested-With': 'XMLHttpRequest'
        }
    }
    _ajax(opt)
}

function getParams() {
    var search = location.search
    search = search.replace('?', '')
    var arr = search.split('&')
    var obj = {}
    for (var item of arr) {
        var list = item.split('=')
        obj[list[0]] = list[1]
    }
  
    return obj
}
function getAccessToken () {
    return new Promise((resolve, reject) => {
        var openid = ''
       

        var code = getParams().code
        if (!code) {
            var url = location.origin + location.pathname
            location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+appid+'&redirect_uri='+url+'&response_type=code&scope=snsapi_base&state=123&connect_redirect=1#wechat_redirect'
            return
        }


        $.ajax({
            url: fytest + "/api/OAuthApi/GetAccessToken?code=" + code,
            success: function (data) {
                var res = JSON.parse(data).Data;
                if (!res.openid) {
                    location.href = location.origin + location.pathname
                    reject()
                    return
                }
                
                openid = res.openid
                resolve(openid)
            }
        });
    })
}

function getUnionID (openid) {
    return new Promise((resolve, reject) => {
        var unionid = $.cookie('unionID')
        if (unionid) {
            resolve(unionid)
            return
        }
        $.ajax({
            url: fytest + "/api/OAuthApi/GetUnionID",
            data: {
                data: JSON.stringify({openid: openid}) 
            },
            success: function (res) {
                res = JSON.parse(res)

                unionid = res.unionid
                resolve(unionid)
            }
        });
    })
}

function getUserInfo ({openid, unionid}){
    return new Promise((resolve, reject) => {
        $.ajax({
            url: appUrl + "/bdc/api/app/users/userInfoByOpenId",
            data: {
                openId:openid, unionId: unionid
            },
            success: function (res) {
              
                resolve(res)
            },
            error: function(err){
                
                reject(err)
            }
        });
    })
}

function loginUser ({loginName, loginPwd, openId, unionId}) {
    return new Promise((resolve, reject) => {
        var params = {loginName, loginPwd, openId, unionId}
        $.ajax({
            url: appUrl + "/bdc/api/app/login/loginResultV2",
            data: params,
            success: function (res) {
                res = JSON.parse(res)
                
                resolve(res)
            }
        });
    })
}

function exit(openId){
    return new Promise((resolve, reject) => {
        var params = {openId: openId}
        $.ajax({
            url: srv + "/apiV2-stucard/api/MOAuth/OpenidDel",
            data: {
                data: JSON.stringify(params)
            },
            success: function (res) {
                res = JSON.parse(res)
                
                resolve(res)
            }
        });
    })
}

function submitLogin() {
    var layerIndex = layer.open({type: 2, shadeClose: false});
    var loginName = $.trim($('#loginName').val())
    var loginPwd = $.trim($('#loginPwd').val())
    var openId = $.cookie('OpenId')
    var unionId = $.cookie('unionID')
    loginUser({loginName, loginPwd, openId, unionId}).then(res => {
        
        
        var result = res
        if (result.message == "ok") {
            localStorage.clear();
            
            var roleCount = 0;
            if (result.data != null && result.data != "") {
                roleCount = result.data.length;
            } else {
                
                layer.open({
                    content: "这个账号角色不是老师或者家长,登录失败",
                    btn: '确定'
                  });
                layer.close(layerIndex);
                exit(openId)
                return;
            }
            if (roleCount == 0) {
               
                layer.open({
                    content: "这个账号角色不是老师或者家长,登录失败",
                    btn: '确定'
                  });
                layer.close(layerIndex);
                exit(openId)
                return;
            }
        

            $.cookie('authToken', JSON.stringify(result.oAuth), {
                path: '/',
                domain: '.xueerqin.net',
                expires: 100
            })

            $.cookie('loginName', loginName, { expires: 100, path: '/', domain: 'xueerqin.net' })
            $.cookie('cellPhoneNum', loginName, { expires: 100, path: '/', domain: 'xueerqin.net' })

            var url = location.origin + location.pathname
            if (roleCount > 1) {
                $.cookie('isMoreRole', true, { expires: 100, path: '/', domain: 'xueerqin.net' })
                location.href = url.replace('static/login.html', 'index.html?v='+ Math.random() +'#/role')
            }
            else {
                $.cookie('isMoreRole', false, { expires: 100, path: '/', domain: 'xueerqin.net' })
            
            
            
                var role = result.data[0].Code;
                $.cookie('roleCode', role, { expires: 100, path: '/', domain: 'xueerqin.net' })
            
                location.href =url.replace('static/login.html', 'index.html?v='+ Math.random() +'#/menu/index')
            }
        } else {
            layer.close(layerIndex);
        }

        if (result.message == "wrongPwd") {
           
            layer.open({
                content: '账号或密码错误 (A)',
                btn: '确定'
              });
        }
        else if (result.message == "invalidUser") {
          
            layer.open({
                content: '账号或密码错误 (B)',
                btn: '确定'
              });
        }
        else if (result.message == "disable") {
          
            layer.open({
                content: '账号或密码错误 (C)',
                btn: '确定'
              });
        }
        else if (result.message == "userBinded") {
           
            layer.open({
                content: '账号已经被登录',
                btn: '确定'
              });
        }
        else if (result.message == "wechatBinded") {
        
            layer.open({
                content: '账号已经被微信绑定登录',
                btn: '确定'
              });
        }
        else if (result.message == "noteacher") {
         
            layer.open({
                content: '您尚未录入教职工信息，请联系管理员添加。',
                btn: '确定'
              });
        }
        else if (result.message == "noparent") {
          
            layer.open({
                content: '您尚未录入家长信息，请联系管理员添加。',
                btn: '确定'
              });
        }
        else if (result.message == "noteacherandparent") {
          
            layer.open({
                content: '您尚未录入教职工和家长信息，请联系管理员添加。',
                btn: '确定'
              });
          
        }
        else {
           
        }
    })

    
}

function start(){
    var layerIndex = layer.open({type: 2, shadeClose: false});
    var openid = $.cookie('OpenId')
    var unionid = $.cookie('unionID')
    getAccessToken().then(res => {
        openid = res
        $.cookie('OpenId', openid, { expires: 100, path: '/', domain: 'xueerqin.net' });
        return getUnionID(openid)
    }).then(res => {
        unionid = res
        $.cookie('unionID', unionid, { expires: 100, path: '/', domain: 'xueerqin.net' });
        return getUserInfo({openid, unionid})
    }).then(res => {
       
        
        $.cookie("loginName", res.loginName, { expires: 100, path: '/', domain: 'xueerqin.net' });
        $.cookie("cellPhoneNum", res.loginName, { expires: 100, path: '/', domain: 'xueerqin.net' });
        
        var url = location.origin + location.pathname
        var roleCount = res.roleCount
        var roles = res.roles
        if (roleCount > 1) {
            
            $.cookie('isMoreRole', true, { expires: 100, path: '/', domain: 'xueerqin.net' })
            location.href = url.replace('static/login.html', 'index.html?v='+ Math.random() +'#/role')
        }
        else if (roleCount == 1) {
            $.cookie('isMoreRole', false, { expires: 100, path: '/', domain: 'xueerqin.net' })
            $.cookie('roleCode', roles[0], { expires: 100, path: '/', domain: 'xueerqin.net' })
          
            location.href = url.replace('static/login.html', 'index.html?v='+ Math.random() +'#/menu/index')
            
        } else if (roleCount == 0) {
            layer.close(layerIndex);
            exit(openid)
        }
       
    }).catch(err => {
        layer.close(layerIndex);
        var res = JSON.parse(err.responseText).error
        if (res.code != 1) {
          
            layer.open({
                content: res.message,
                btn: '确定'
              });
        }
        layer.close(layerIndex);
    })

}

start()